package com.mikao.service.impl;

import com.mikao.constant.CommonConstant;
import com.mikao.constant.RedisKeyPrefix;
import com.mikao.service.AuthService;
import com.mikao.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 授权Service实现类
 *
 * @author KennyDavid
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public String createToken(Long userId) {
        String token = JwtUtil.createToken(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        log.info(String.valueOf(userId));
        redisTemplate.opsForValue().set(RedisKeyPrefix.USER_TOKEN + userId, map, 15, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Boolean validateToken(Long userId, String token) {
        Map<String, String> obj = (Map<String, String>) redisTemplate.opsForValue().get(RedisKeyPrefix.USER_TOKEN + userId);
        if (!ObjectUtils.isEmpty(obj) && token.equals(String.valueOf(obj.get("token")))) {
            redisTemplate.expire(CommonConstant.USER_TOKEN + userId, 15, TimeUnit.DAYS);
            return true;
        }
        return false;
    }
}
